<template>
  <div
    v-if="imgList.length === 0"
    class="placeholder flex flex-col items-center justify-center h-[100%]">
    <img src="@/assets/common/empty.png" alt="" class="w-[64px] h-[64px] mb-[4px]" />
    <div class="text-[#7A7A7A] text-[16px]">Please use AI to create your design</div>
    <div class="text-[#7A7A7A] text-[16px]" v-if="isAid">
      Click the "Post" button to publish your design post and enter the contest.
    </div>
  </div>
  <div class="img_container" v-else>
    <!-- 操作栏 -->
    <div class="flex_row_s header mb-[24px] h-[25px]">
      <span>Results</span>
      <div class="flex_row">
        <div v-if="isEdit" class="flex_row">
          <el-tooltip effect="dark" content="Download" placement="top">
            <DownloadIcon class="mr-[16px] cursor_poi" @click="downImg" />
          </el-tooltip>
          <el-tooltip effect="dark" content="Delete" placement="top">
            <DeleteIcon class="mr-[24px] cursor_poi" @click="batchDeleteImg" />
          </el-tooltip>
          <CloseIcon />
        </div>
        <span @click="editImg" class="cursor_poi line ml-[2px]" v-slide-underline>
          {{ isEdit ? 'Deselect' : 'Bulk Edit' }}
        </span>
      </div>
    </div>
    <!-- 作品区块 -->
    <div v-for="item in imgList" :key="item.uid" class="mb-[40px]">
      <!-- 作品信息 -->
      <div class="flex_row_s">
        <div class="flex_row time_des">
          <span class="mr-[8px]">{{ item.created_at }}</span>
          <LineIcon />
          <span class="bold ml-[8px] mr-[8px] col_222">
            {{ getGenTypeText(item.gen_template?.gen_type) }}
          </span>
          <LineIcon v-if="item.gen_template?.name" />
          <span class="ml-[8px]" v-if="item.gen_template?.name">{{ item.gen_template.name }}</span>
        </div>
      </div>
      <!-- 作品提示词 -->
      <div class="img_des mt-[8px] mb-[16px]">{{ item.prompt_text }}</div>
      <!-- 图片列表 -->
      <div class="img_view" v-if="item.imgs && item.imgs.length > 0">
        <div
          v-for="imgItem in item.imgs"
          :key="imgItem.id"
          class="select_view cursor_poi"
          @click="goDetail(item, imgItem)"
          @mouseenter="showModal(imgItem.id)"
          @mouseleave="hideModal(imgItem.id)">
          <el-skeleton
            v-if="item.status === TaskType.PROCESSING"
            width="100%"
            height="100%"
            style="aspect-ratio: 1"
            class="image-skeleton"
            :animated="true">
            <template #template>
              <el-skeleton-item
                variant="image"
                style="width: 100%; height: 100%; border-radius: 8px" />
            </template>
          </el-skeleton>
          <SvgIcon
            v-else-if="item.status === TaskType.FAIL"
            style="width: 100%; height: 100%"
            name="ai-image-error" />
          <div class="img-container" v-else>
            <img class="img_item" :src="imgItem.url" alt="" />
            <!-- 批量编辑按钮 -->
            <div class="edit_btns" v-if="isEdit" @click="selectImg(imgItem)">
              <CheckedIcon v-if="imgItem.isCheck" />
              <CheckIcon v-else />
            </div>
            <!-- 添加鼠标hover时显示的modal -->
            <div class="img_modal" v-if="!isEdit && visibleModalId === imgItem.id">
              <div class="modal_content">
                <div class="modal_actions">
                  <el-tooltip content="Download" placement="top">
                    <div class="action_icon" @click.stop="downloadSingleImage(imgItem.url)">
                      <SvgIcon name="ai-feed-download" size="22" />
                    </div>
                  </el-tooltip>
                  <el-tooltip content="Post" placement="top">
                    <div class="action_icon" @click.stop="publishImage(imgItem)">
                      <SvgIcon name="ai-feed-post" size="22" />
                    </div>
                  </el-tooltip>
                </div>
                <div class="bottom_actions">
                  <div class="icons">
                    <el-tooltip content="Image to Image" placement="top">
                      <SvgIcon name="ai-feed-img2" size="22" @click.stop="goImg2Img(imgItem)" />
                    </el-tooltip>
                    <el-tooltip content="Edit Image Details" placement="top">
                      <SvgIcon name="ai-feed-edit" size="22" @click.stop="goEdit(imgItem)" />
                    </el-tooltip>
                    <el-tooltip content="Upscale" placement="top">
                      <SvgIcon name="ai-feed-hd" size="22" @click.stop="goHd(imgItem)" />
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import { downloadImage, packImagesToZip } from '@/utils/tools';
  import { AiAPI } from '@/api/ai';
  import { bus } from '@/utils/bus';
  import { AIType, TaskType } from '@/types/ai';
  import CloseIcon from './icons/CloseIcon.vue';
  import LineIcon from './icons/LineIcon.vue';
  import CheckedIcon from './icons/CheckedIcon.vue';
  import CheckIcon from './icons/CheckIcon.vue';
  import { useAiStore } from '@/store/ai';
  import { ElMessageBox } from 'element-plus';
  import DownloadIcon from '@/components/icons/ai/DownloadIcon.vue';
  import DeleteIcon from '@/components/icons/ai/DeleteIcon.vue';

  const props = defineProps({
    list: { type: Array, default: () => [] },
    showDelete: { type: Boolean, default: false },
  });
  const isEdit = ref<Boolean>(false);
  const imgList = ref<any>([]);
  const visibleModalId = ref<number | null>(null); // 用于控制哪个图片的modal显示
  const router = useRouter();

  const aiStore = useAiStore();

  const isAid = computed(() => !!router.currentRoute.value.query.aid);

  // 监听props.list变化，保持本地数据同步更新
  watch(
    () => props.list,
    (newList) => {
      imgList.value = newList;
    },
    {
      immediate: true, // 立即执行一次
      deep: true, // 深度监听
    }
  );

  // 跳转图片详情
  const goDetail = (item: any, imgItem: any) => {
    // 确保在编辑模式下不执行跳转
    if (!isEdit.value && item.status == TaskType.SUCCESS) {
      // 根据item数据结构，使用router.push跳转到详情页并传递task_id参数
      router.push({
        path: '/generator/detail',
        query: {
          ...router.currentRoute.value.query,
          task_id: item.task_id, // 假设item.id是任务ID
          img_id: imgItem.id,
        },
      });
    }
  };

  const selectImg = (selectItem: any) => {
    imgList.value?.forEach((item: any) => {
      item?.imgs?.forEach((img: any) => {
        if (selectItem?.id === img.id) {
          img.isCheck = !img.isCheck;
          console.log('temp', img);
        }
      });
    });
  };

  const editImg = () => {
    // 如果当前是编辑模式，在切换前清除所有选中状态
    if (isEdit.value) {
      // 清除imgList中所有图片的选中状态
      imgList.value?.forEach((item: any) => {
        item?.imgs?.forEach((img: any) => {
          img.isCheck = false;
        });
      });
    }

    isEdit.value = !isEdit.value;
  };

  // 批量下载图片
  const downImg = () => {
    const list: any = [];
    imgList.value?.forEach((item: any) => {
      item?.imgs?.forEach((img: any) => {
        img.isCheck && list.push(img.url);
      });
    });
    if (list.length === 0) return;
    list.length === 1 ? downloadImage(list[0]) : packImagesToZip(list);
  };

  // 批量删除选中图片
  const batchDeleteImg = async () => {
    const list: any = [];
    imgList.value?.forEach((item: any) => {
      item?.imgs?.forEach((img: any) => {
        img.isCheck && list.push(img);
      });
    });
    if (list.length === 0) return;
    try {
      // 显示确认对话框
      await ElMessageBox.confirm(
        'Deleting this image will remove it permanently and clear all drawn masks',
        'Delete this image?',
        {
          confirmButtonText: 'Delete',
          cancelButtonText: 'Cancel',
          center: true,
          showClose: false,
          customClass: 'delete-confirm-dialog',
        }
      );
      const tasks = list.map((item: any) => ({
        task_id: item.task_id,
        img_ids: [item.id],
      }));

      await AiAPI.deleteGenerateImg({ tasks });
      // 删除成功后，刷新图片列表
      aiStore.getGenerateResults();
      isEdit.value = false;
    } catch {}
  };

  // 显示modal
  const showModal = (id: number) => {
    visibleModalId.value = id;
  };

  // 隐藏modal
  const hideModal = (id: number) => {
    visibleModalId.value = null;
  };

  // 下载单个图片
  const downloadSingleImage = (url: string) => {
    downloadImage(url);
  };

  // 发布图片
  const publishImage = (imgItem: any) => {
    // 这里可以添加发布图片的逻辑
    bus.emit('open:post', {
      image: imgItem.url,
      prompt: imgItem.prompt_text,
    });
  };

  // 跳转图生图
  const goImg2Img = (imgItem: any) => {
    router.push({
      path: '/generator/img2img',
      query: {
        ...router.currentRoute.value.query,
        img: encodeURIComponent(imgItem.url),
      },
    });
  };

  // 跳转编辑
  const goEdit = (imgItem: any) => {
    router.push({
      path: '/generator/edit',
      query: {
        ...router.currentRoute.value.query,
        img: encodeURIComponent(imgItem.url),
      },
    });
  };

  // 跳转高修图
  const goHd = (imgItem: any) => {
    router.push({
      path: '/generator/hd',
      query: {
        ...router.currentRoute.value.query,
        img: encodeURIComponent(imgItem.url),
      },
    });
  };

  // 计算属性：获取生成类型的显示文本
  const getGenTypeText = computed(() => {
    return (genType: number) => {
      switch (genType) {
        case AIType.TEXT:
          return 'Text to Image';
        case AIType.IMAGE:
          return 'Image to Image';
        case AIType.EDIT:
          return 'Edit Image Details';
        case AIType.HD:
          return 'Upscale';
        default:
          return '';
      }
    };
  });
</script>

<style lang="scss" scoped>
  @use '@/styles/mixins' as *;
  .img_container {
    width: 100%;
    background: #f8f8f8;
    padding: 16px 40px;
  }

  .cursor_poi {
    cursor: pointer;
  }

  .col_222 {
    color: #222;
  }

  .header {
    color: #222;
    font-size: 16px;
    font-style: normal;
    font-weight: 600;
    line-height: normal;
  }

  .edit_btns {
    position: absolute;
    right: 4px;
    top: 4px;
  }

  .img_view {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: px-to-vw(24);
    .select_view {
      position: relative;
      overflow: hidden;
      aspect-ratio: 1 / 1;
      .img-container {
        height: 100%;
        .img_item {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 5px;
          transition: filter 0.2s ease;
        }
      }
    }
  }

  // Modal相关样式
  .img_modal {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    transition: opacity 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .modal_content {
    position: relative;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 12px;
  }

  .modal_actions {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
    .action_icon {
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      padding: 4px;
      background: rgba(255, 255, 255, 0.8);
      border-radius: 8px;
      backdrop-filter: blur(2px);
      &:hover {
        background: rgba(255, 255, 255, 0.6);
      }
    }
  }

  .bottom_actions {
    display: flex;
    justify-content: flex-end;
    .icons {
      display: flex;
      justify-content: flex-end;
      gap: 16px;
      border-radius: 8px;
      background: rgba(255, 255, 255, 0.8);
      backdrop-filter: blur(2px);
      padding: 4px 8px;
      width: fit-content;
      &:hover {
        background: rgba(255, 255, 255, 0.6);
      }
    }
  }

  .preview_icon {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    align-self: flex-end;
  }

  .select_view:hover .img_modal {
    opacity: 1;
  }

  .select_view:hover .img_item {
    filter: brightness(0.8);
  }

  .img_des {
    color: #222;
    font-size: 14px;
    font-weight: 500;
    line-height: 21px;
    max-width: 1192px;
  }

  .time_des {
    border-radius: 8px;
    background: #ededed;
    padding: 8px 12px;
    color: #7a7a7a;
    font-size: 14px;
    font-weight: 500;
    width: auto;
  }

  .line {
    display: inline-block;
    background-image: linear-gradient(to right, #cbcbcb, #cbcbcb);
    background-size: 100% 1px;
    background-position: bottom;
    background-repeat: no-repeat;
  }

  .flex_row {
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .flex_row_s {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
</style>
